import React,{useState,useImperativeHandle} from 'react'

function ImperativeChild (props,ref) { // 接收
    const [count,setCount] = useState(0)
    const addCount = () => {
        setCount(count + 1)
    }
    const subCount = () => {
        setCount(count -1)
    }
    //子组件通过useImperativeHandle函数，将addCount函数添加到父组件中的ref.current中
    useImperativeHandle(ref,() =>({addCount,subCount}))
    return (
        <div>
            {count}
            <button onClick={addCount}>add</button>
        </div>
    )
}
//子组件导出时需要被React.forwardRef包裹，否则无法接收 ref这个参数
export default React.forwardRef(ImperativeChild)
